<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionClass :class-id="listQuery.class_id" @setSearchClassId="searchClassId" />
      <el-input v-model="listQuery.title" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center">
        <template slot-scope="{row}">
          <span>{{ row.classInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center">
        <template slot-scope="{row}">
          <span>{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center">
        <template slot-scope="{row}">
          <span :style="isTopClass(row.is_top)">{{ isTopConfig[row.is_top] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评论数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="userInfo">
          <el-input v-model="temp.userInfo.name" />
        </el-form-item>
        <el-form-item v-model="temp.class_id" label="班级" prop="class_id" class="filter-item">
          <SearchOptionClass :class-id="temp.class_id" @setSearchClassId="updateClassId" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="temp.content" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="is_top">
          <el-select v-model="temp.is_top" class="filter-item">
            <el-option v-for="(value,key) in isTopConfig" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="created_at">
          <el-date-picker v-model="temp.created_at" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="评论数" prop="num">
          <el-input-number v-model="temp.num" @change="handleChange" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { classDiscussPage, classShareUpdate, classDiscussDel } from '@/api/class' // classSharePage, classShareUpdate, classShareDelete  classDiscussAdd, classDiscussDel
import waves from '@/directive/waves' // waves directive
import { notifySuccess, formatJson, my_confirm, listQueryFilter } from '@/utils/tool'
import Pagination from '@/components/Pagination'
import SearchOptionClass from '@/components/SearchOption/class'

export default {
  name: 'ClassSharePage',
  components: { Pagination, SearchOptionClass },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        class_id: null
        // title: null,
        // url: null
      },
      temp: {
        id: null,
        class_id: null,
        classInfo: {},
        user_id: '',
        userInfo: {},
        content: '',
        is_top: '',
        created_at: '',
        num: '',
        parent_id: null
        // title: null,
        // url: null
      },
      isTopConfig: { 0: '否', 1: '是' },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        creasadasdaste: '添加'
      },
      rules: {
        userInfo: [{ required: true, message: '姓名必填', trigger: 'change' }],
        class_id: [{ required: true, message: '班级必填', trigger: 'change' }],
        content: [{ required: true, message: '内容必填', trigger: 'change' }],
        is_top: [{ required: true, message: '是否置顶必填', trigger: 'change' }],
        created_at: [{ required: true, message: '发布必填', trigger: 'change' }],
        num: [{ required: true, message: '评论数必填', trigger: 'change' }]
        // title: [{ required: true, message: '班级名称必填', trigger: 'change' }],
        // url: [{ required: true, message: '分享地址必填必填', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      classDiscussPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 如果置顶则字变红
    isTopClass(n) {
      if (n === '1') {
        return 'color: #FF0000'
      }
    },
    resetTemp() {
      this.temp = {
        class_id: null,
        id: null,
        classInfo: {},
        user_id: '',
        userInfo: {},
        content: '',
        is_top: '',
        created_at: '',
        num: '',
        parent_id: null
        // title: null,
        // url: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          classShareUpdate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.class_id = row.class_id
      this.temp.classInfo = row.classInfo
      this.temp.user_id = row.user_id
      this.temp.userInfo = row.userInfo
      this.temp.content = row.content
      this.temp.is_top = row.is_top
      this.temp.created_at = row.created_at
      this.temp.num = row.num
      // this.temp.title = row.title
      // this.temp.url = row.url
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          classShareUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        classDiscussDel({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['班级ID', '名称']
        const filterVal = ['class_id', 'title']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '分享教室'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    searchClassId: function(data) {
      this.listQuery.class_id = data.classId
    },
    updateClassId: function(data) {
      this.temp.class_id = data.classId
    },
    handleChange(value) {
      // console.log('value:' + value)
    }
  }
}
</script>
